<?php

namespace App\Http\Middleware;

use App\Modules\User\Services\UserService;
use Closure;
use Illuminate\Support\Facades\Log;
use Redis;
use Illuminate\Http\Request;

class WebAuth
{
    /**
     * 判断是否微信已授权.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {


        try{
            $token =UserService::getInfoFromToken();
            $request->attributes->add(compact('token'));
        }catch (\Exception $e){

            if($e->getCode() == 10080){
                return response()->error('TOKEN_EXPIRE');
            }
            Log::error('get token error:'.$e->getMessage().$e->getCode());
            return response()->error('TOKEN_INVALID');
        }
        if($token == false) {
            return response()->error('NOT_LOGIN');
        }
        \Log::info($token);
        if(!isset($token['id'])) {
            return response()->error('NOT_LOGIN');
        }
        $previous_token = \Redis::get('app_login:'.$token['id']);
        \Log::info($previous_token);
        \Log::info($request->header('Authorization'));

        if(str_replace('Bearer ','',$request->header('Authorization')) != $previous_token) {
            return response()->error('NOT_LOGIN');
        }

        $response = $next($request);
        return $response;
    }
}
